package special;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import util.Pair;

/**
 * @author Grega
 */
public class Graph
{
  HashMap<Pair, Double> E;

  public Graph()
  {
    E = new HashMap<Pair, Double>();
  }

  public boolean addEdge(Integer v1, Integer v2)
  {
    if (E.get(new Pair(v1, v2)) != null) {
      return true;
    }
    E.put(new Pair(v1, v2), new Double(-1));
    return false;
  }

  public boolean addEdge(Integer v1, Integer v2, Double value)
  {
    if (E.get(new Pair(v1, v2)) != null) {
      return true;
    }
    E.put(new Pair(v1, v2), value);
    return false;
  }

  public boolean setEdge(Integer v1, Integer v2, Double value)
  {
    if (E.get(new Pair(v1, v2)) != null) {
      E.put(new Pair(v1, v2), value);
      return true;
    }
    return false;
  }

  public boolean removeEdge(Integer v1, Integer v2)
  {
    if (E.get(new Pair(v1, v2)) != null) {
      E.remove(new Pair(v1, v2));
      return true;
    }
    return false;
  }

  public Double[][] exportEdgeTable()
  {
    Double[][] table;
    int maximum = -1;
    Iterator<Entry<Pair, Double>> it = E.entrySet().iterator();

    while (it.hasNext()) {
      Entry<Pair, Double> e = it.next();
      // e.getKey().v1 testovat nemusime, z def. UnorderedPair vieme, ze v1<v2
      if (e.getKey().v2 > maximum) {
        maximum = e.getKey().v2;
      }
    }
    maximum++;
    table = new Double[maximum][maximum];
    for (int i = 0; i < table.length; i++) {
      for (int j = 0; j < table[i].length; j++) {
        if (E.get(new Pair(i, j)) == null || E.get(new Pair(i, j)) < 0) {
          table[i][j] = -1.0;
        } else {
          table[i][j] = E.get(new Pair(i, j));
        }
      }
    }
    return table;
  }

}
